package com.moss.cloud.log.message;


import com.alibaba.fastjson2.JSON;
import com.moss.cloud.common.core.constant.MsgGroup;
import com.moss.cloud.common.core.constant.MsgTopic;
import com.moss.cloud.common.core.model.dto.MessageDTO;
import com.moss.cloud.common.core.model.dto.UserLoginDTO;
import com.moss.cloud.log.model.po.LoginLog;
import com.moss.cloud.log.service.ILoginLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;

/**
 * 消息管理-监听用户登录事件，保存登录日志
 * 广播模式 MessageModel.BROADCASTING
 *
 * @author 瑾年
 * @date 2020/05/15
 */
@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = MsgGroup.MOSS_CLOUD_BASE, topic = MsgTopic.USER_LOGIN_MESSAGE, messageModel = MessageModel.BROADCASTING)
public class ListenerLoginMessage implements RocketMQListener<MessageDTO> {
    private final ILoginLogService loginLogService;

    public ListenerLoginMessage(ILoginLogService loginLogService) {
        this.loginLogService = loginLogService;
    }

    /**
     * 监听用户登录MQ消息
     *
     * @param messageDTO
     * @return void
     * @author 瑾年
     * @date 2020/05/15
     */
    @Override
    public void onMessage(MessageDTO messageDTO) {
        log.info("登录用户消费者获取消息:{}", messageDTO.toString());
        LinkedHashMap data = (LinkedHashMap) messageDTO.getData();
        log.info("用户登录对象:{}", data.toString());
        UserLoginDTO dto = JSON.parseObject(JSON.toJSONString(data), UserLoginDTO.class);
        LoginLog loginLog = new LoginLog();
        BeanUtils.copyProperties(dto, loginLog);
        loginLog.setUserName(dto.getAccountNumber());
        loginLogService.saveLoginLog(loginLog);
    }
}
